const fs = require('fs')
const path = require('path')
const express = require('express')
const bodyParser = require('body-parser')
const { createProxyMiddleware } = require('http-proxy-middleware')
const jsonPath = path.resolve(__dirname, './public/proxyConfig.json')
const { port } = require('./config')
const app = express()

let proxyConfig = null
try {
  proxyConfig = require(jsonPath)
} catch (error) {
  console.log('proxyConfig 不存在')
}
function valiConfig(data) {
  return data?.value && Array.isArray(data.configList) && data.configList.length
}

// 跨域设置
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', '*')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('X-Powered-By', '3.2.1')
  if (req.method === 'OPTIONS') {
    res.send(200)
  } else {
    next()
  }
})

// 静态文件目录设置
app.use(express.static(path.resolve(__dirname, './public')))
// 代理服务器配置
function setProxy() {
  if (!valiConfig(proxyConfig)) return
  const cur = proxyConfig.configList.find((e) => e.value == proxyConfig.value)
  for (let item of cur.proxyList) {
    if (!item.value) continue
    const option = {
      target: item.value,
      changeOrigin: true,
      pathRewrite: { [`^${item.head}`]: '' },
      onProxyReq: function (proxyReq, req, res) {
        // 打印请求日志
        if (item.requestLog == 1) {
          console.log(
            `ip: ${req.ip} [ ${req.method} ${req.baseUrl} ${req.url} ]`
          )
        }
      }
    }
    app.use(item.head, createProxyMiddleware(option))
  }
}
setProxy()

/**
 * bodyParser 中间件必须放到代理服务器配置后面
 * 否则会导致 post 请求返回的数据被再次处理导致无法返回
 */
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
/**保存列表-内部接口 */
app.use('/p-api/saveProxy', (req, res, next) => {
  const data = req.body
  if (valiConfig(data)) {
    setTimeout(() => {
      fs.writeFileSync(path.resolve(__dirname, jsonPath), JSON.stringify(data))
    }, 10)
    res.send({ code: 0, message: '操作成功' })
  } else {
    res.send({ code: 5, message: '操作失败' })
  }
})

// 404
app.use((req, res, next) => {
  if (res.status(404)) {
    res.send('404：请求地址不存在')
  }
  next()
})

app.listen(port)

/**获取 本机 ip 地址 */
function getIPAddress() {
  var interfaces = require('os').networkInterfaces()
  for (var devName in interfaces) {
    var iface = interfaces[devName]
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i]
      if (
        alias.family === 'IPv4' &&
        alias.address !== '127.0.0.1' &&
        !alias.internal
      ) {
        return alias.address
      }
    }
  }
}
console.log(
  '\x1B[33m%s\x1b[0m:',
  `
============= [打开一下链接进行可视化配置] =============
- Local:     http://localhost:${port}
- Network:   http://${getIPAddress()}:${port}
======================================================
`
)
